//
//  PhotoDataProvider.m
//  PigMarket
//
//  Created by Felix on 2019/3/20.
//  Copyright © 2019 felix.pigmarket.oc. All rights reserved.
//

#import "PhotoDataProvider.h"
#import <Photos/Photos.h>

// 沙盒路径
#define PhotoDataPath [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"photoData"]
#define AssetsDataPath [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"assetsData"]

@interface PhotoDataProvider ()

@end

@implementation PhotoDataProvider

@synthesize currentPhotos = _currentPhotos;
@synthesize currentAssets = _currentAssets;

+ (PhotoDataProvider *)sharedInstance {
    static PhotoDataProvider *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[PhotoDataProvider alloc] init];
    });
    return instance;
}

- (void)setCurrentPhotos:(NSMutableArray *)currentPhotos {
    _currentPhotos = currentPhotos;
    if (currentPhotos.count > 0) {
        [NSKeyedArchiver archiveRootObject:currentPhotos toFile:PhotoDataPath];
    } else {
        NSFileManager *defaultManager = [NSFileManager defaultManager];
        if ([defaultManager isDeletableFileAtPath:PhotoDataPath]) {
            [defaultManager removeItemAtPath:PhotoDataPath error:nil];
        }
    }
}
- (NSMutableArray *)currentPhotos {
    if (!_currentPhotos) {
        _currentPhotos = [NSKeyedUnarchiver unarchiveObjectWithFile:PhotoDataPath];
    }
    return _currentPhotos;
}

- (void)setCurrentAssets:(NSMutableArray *)currentAssets {
    _currentAssets = currentAssets;
    NSMutableArray *localIdentifiers = [NSMutableArray array];
    for (PHAsset *item in currentAssets) {
        [localIdentifiers addObject:item.localIdentifier];
    }
    
    if (currentAssets.count > 0) {
        [NSKeyedArchiver archiveRootObject:localIdentifiers toFile:AssetsDataPath];
    } else {
        NSFileManager *defaultManager = [NSFileManager defaultManager];
        if ([defaultManager isDeletableFileAtPath:AssetsDataPath]) {
            [defaultManager removeItemAtPath:AssetsDataPath error:nil];
        }
    }
}
- (NSMutableArray *)currentAssets {
    if (!_currentAssets) {
        NSArray *localIdentifiers = [NSKeyedUnarchiver unarchiveObjectWithFile:AssetsDataPath];
        NSMutableArray *tempArray = [NSMutableArray array];
        if (localIdentifiers.count > 0) {
            PHFetchResult *fetchResult = [PHAsset fetchAssetsWithLocalIdentifiers:localIdentifiers options:nil];
            for (PHAsset *item in fetchResult) {
                [tempArray addObject:item];
            }
        }
        _currentAssets = tempArray;
    }
    return _currentAssets;
}

@end
